package interview.a1b2c3;


import java.util.concurrent.locks.LockSupport;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-12-19 11:23
 **/

/**
 * 两个线程分别输出 A-Z 和 1-26 ，
 * 要求两个线程交替输出
 * 即：A1B2C3D4
 */

public class Test_05_LockSupport {
    public static final String[] LETTER_ARRAY = new String[]{"A", "B", "C", "D", "E", "F"};
    public static final String[] NUMBER_ARRAY = new String[]{"1", "2", "3", "4", "5", "6"};
    static Thread thread_1 = null, thread_2 = null;


    /**
     * LockSupport.unpark(thread_2);  LockSupport.park() 和 Object.notify/wait 比较：
     * 1、以thread为操作对象更符合阻塞线程的直观定义
     * 2、操作更精准，可以准确地唤醒某一个线程（notify随机唤醒一个线程，notifyAll唤醒所有等待的线程），增加了灵活性
     */

    public static void main(String[] args) {
        thread_1 = new Thread(() -> {
            try {
                for (String str : LETTER_ARRAY) {
                    System.err.println(str);
//                    解除阻塞，支持指定线程，灵活控制
                    LockSupport.unpark(thread_2);
//                    阻塞当前线程
                    LockSupport.park();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        thread_2 = new Thread(() -> {
            try {
                for (String str : NUMBER_ARRAY) {
                    LockSupport.park();
                    System.err.println(str);
                    LockSupport.unpark(thread_1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        thread_1.start();
        thread_2.start();
    }
}
